﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Data.SqlClient;
using System.IO;

namespace SqlServerPacker {
	public partial class FormPacker : Form {
		BackgroundWorker bw = new BackgroundWorker();
		string serverName = string.Empty;

		public FormPacker() {
			InitializeComponent();
			bw.DoWork += new DoWorkEventHandler(bw_DoWork);
			bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
		}

		void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {

			if (comboBox1.Text != "正在检索...") {
				serverName = comboBox1.Text;
			}

			if (e.Result == null) {
				comboBox1.DroppedDown = false;
			}
			comboBox1.Items.Clear();
			if (e.Result != null) {
				comboBox1.Items.AddRange(e.Result as string[]);
			}
		}

		void bw_DoWork(object sender, DoWorkEventArgs e) {
			Thread.Sleep(5000);
			e.Result = new string[] { "(local)", "(local)\\SQL15" };
		}

		private void button1_Click(object sender, EventArgs e) {
			SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
			builder.DataSource = ".\\sqlexpress";
			builder.InitialCatalog = "MCDEXWeb";
			builder.IntegratedSecurity = true;
			SqlConnection conn = new SqlConnection(builder.ConnectionString);
			conn.Open();
			DataTable dt = conn.GetSchema("Tables");
			StringBuilder cmdBuilder = new StringBuilder();
			StringBuilder import = new StringBuilder();
			for (int i = 0; i < dt.Rows.Count; i++) {
				if (dt.Rows[i]["TABLE_TYPE"].ToString() == "BASE TABLE") {
					//bcp AdventureWorks.sales.currency out c:\currency1.txt -c -U"sa" -P"password" --使用密码连接或bcp AdventureWorks.sales.currency out c:\currency1.txt -c -T --使用信任连接,在使用密码登录时需要将-U后的用户名和-P后的密码加上双引号。
					//bcp AdventureWorks.sales.currency1 in c:\currency1.txt -c -T
					//bcp web_pi_display format nul -f D:\Projects\SqlServerPacker\data\pi_display.fmt -S.\sqlexpress -U"mcdex" -P"mcdex" -d mcdexweb -n
					//bcp web_pi_display out D:\Projects\SqlServerPacker\data\pi_display.data -S.\sqlexpress -U"mcdex" -P"mcdex" -d mcdexweb -n
					//BULK INSERT bulktest..t_float FROM 'C:\t_float-c.dat' WITH (FORMATFILE='C:\t_floatformat-c-xml.xml');
					string datafile = dt.Rows[i]["TABLE_NAME"].ToString() + ".dat";// Path.Combine(Application.StartupPath, dt.Rows[i]["TABLE_NAME"].ToString() + ".dat");
					string fmtfile = dt.Rows[i]["TABLE_NAME"].ToString() + ".fmt";// Path.Combine(Application.StartupPath, dt.Rows[i]["TABLE_NAME"].ToString() + ".fmt");
					cmdBuilder.AppendFormat("bcp {0} format nul -f {1} -S.\\sqlexpress -U\"mcdex\" -P\"mcdex\" -d mcdexweb -n\r\n", dt.Rows[i]["TABLE_NAME"].ToString(), fmtfile);

					//cmdBuilder.AppendFormat("bcp {0} out {1} -f {2} -S.\\sqlexpress -U\"mcdex\" -P\"mcdex\" -d mcdexweb -n\r\n", dt.Rows[i]["TABLE_NAME"].ToString(), datafile, fmtfile);
					cmdBuilder.AppendFormat("bcp {0} out {1} -S.\\sqlexpress -U\"mcdex\" -P\"mcdex\" -d mcdexweb -n\r\n", dt.Rows[i]["TABLE_NAME"].ToString(), datafile);
					import.AppendFormat("bcp {0} in {1} -f {2} -S.\\sqlexpress -U\"mcdex\" -P\"mcdex\" -d test\r\n", dt.Rows[i]["TABLE_NAME"].ToString(), datafile, fmtfile);
				}
			}
			File.WriteAllText(Path.Combine(Application.StartupPath, "export.bat"), cmdBuilder.ToString());
			File.WriteAllText(Path.Combine(Application.StartupPath, "import.bat"), import.ToString());
		}

		private void ExecProcess(string filename, string arguments) {
			using (Process process = new Process()) {
				process.StartInfo.FileName = filename;
				process.StartInfo.Arguments = arguments;
				process.StartInfo.WorkingDirectory = Application.StartupPath;
				process.StartInfo.UseShellExecute = false;
				process.StartInfo.CreateNoWindow = true;
				//process.StartInfo.RedirectStandardOutput = true;
				//process.StartInfo.RedirectStandardError = true;
				process.Start();
				//string output = process.StandardOutput.ReadToEnd();
				//string error = process.StandardError.ReadToEnd();
				process.WaitForExit();
				process.Close();
			}
		}

		private void comboBox1_DropDown(object sender, EventArgs e) {
			if (!bw.IsBusy && comboBox1.Items.Count == 0) {
				comboBox1.Items.Add("正在检索...");
				bw.RunWorkerAsync();
			}
		}

		private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e) {
			if (comboBox1.Text != "正在检索...") {
				serverName = comboBox1.Text;
			}
		}

		private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
			if (comboBox1.Text == "正在检索...") {
				comboBox1.SelectedItem = null;
				comboBox1.Text = serverName;
			}
		}
	}
}
